package com.fy.fyspace.controller;

import com.fy.fyspace.common.annotation.GlobalInterceptor;
import com.fy.fyspace.common.result.R;
import com.fy.fyspace.constant.KeysConstant;
import com.fy.fyspace.constant.ResultMessageConstant;
import com.fy.fyspace.ex.handler.ExHandler;
import com.fy.fyspace.mapper.PictureCategoryMapper;
import com.fy.fyspace.mapper.PictureTagMapper;
import com.fy.fyspace.model.dto.picture.*;
import com.fy.fyspace.model.entity.PictureCategory;
import com.fy.fyspace.model.entity.PictureTag;
import com.fy.fyspace.model.vo.user.UserSessionVO;
import com.fy.fyspace.service.PictureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.fy.fyspace.common.result.R.no;
import static com.fy.fyspace.common.result.R.ok;

/**
 * 图片管理控制器
 */
@Api(tags = "图片管理接口")
@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController extends BaseController {

    @Resource
    private PictureCategoryMapper pictureCategoryMapper;

    @Resource
    private PictureTagMapper pictureTagMapper;

    @Resource
    private PictureService pictureService;

    @Resource
    private HttpSession httpSession;

    /**
     * 获取图片分类列表
     */
    @ApiOperation(value = "获取图片分类列表", notes = "获取系统支持的所有图片分类")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 400, message = "服务器内部错误")
    })
    @GetMapping("/categories")
    public R getCategories() {
        List<PictureCategory> categories = pictureCategoryMapper.selectList(null);
        Set<String> categoryNames = new HashSet<>();
        for (PictureCategory category : categories) {
            categoryNames.add(category.getCategoryName());
        }
        return ok(categoryNames);
    }

    /**
     * 获取图片标签列表
     */
    @ApiOperation(value = "获取图片标签列表", notes = "获取系统支持的所有图片标签")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 400, message = "服务器内部错误")
    })
    @GetMapping("/tags")
    public R getTags() {
        List<PictureTag> tagList = pictureTagMapper.selectList(null);
        Set<String> tagNameList = new HashSet<>();
        for (PictureTag tag : tagList) {
            tagNameList.add(tag.getTagName());
        }
        return ok(tagNameList);
    }

    /**
     * 获取图片列表
     */
    @ApiOperation(value = "获取图片列表", notes = "获取图片列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 400, message = "获取失败"),
    })
    @GetMapping("/list")
    public R getPictureList(PictureListQueryDTO queryDTO){
        return pictureService.getPictureList(queryDTO);
    }

    /**
     * 单个或批量上传图片
     */
    @ApiOperation("单个或批量上传图片")
    @PostMapping("/upload")
    @GlobalInterceptor
    public R uploadImages(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(required = false) String prefix,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String description,
            @RequestParam(defaultValue = "1") Integer isPublic) {
        log.info("上传图片/prefix:{}", prefix);
        log.info("上传图片/tags:{}", tags);
        log.info("上传图片/category:{}", category);
        log.info("上传图片/description:{}", description);
        log.info("上传图片/isPublic:{}", isPublic);
        return pictureService.uploadImages(files, prefix, tags, category, description, isPublic);
    }

    // 获取图片统计数据
    @ApiOperation(value = "获取图片统计数据", notes = "获取图片统计数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功"),
            @ApiResponse(code = 400, message = "获取失败"),
    })
    @GetMapping("/statistics")
    @GlobalInterceptor
    public R getStatistics() {
        return pictureService.getStatistics();
    }

    /**
     * 获取图片详情
     */
    @ApiOperation(value = "获取图片详情", notes = "获取指定图片的详细信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功"),
        @ApiResponse(code = 400, message = "获取失败")
    })
    @GetMapping("/{pictureId}")
    public R getPictureDetail(@PathVariable Long pictureId) {
        return pictureService.getPictureDetail(pictureId);
    }

    /**
     * 更新图片信息
     */
    @ApiOperation(value = "更新图片信息", notes = "更新指定图片的基本信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "更新成功"),
        @ApiResponse(code = 400, message = "更新失败")
    })
    @PutMapping("/{pictureId}")
    @GlobalInterceptor
    public R updatePicture(
            @PathVariable Long pictureId,
            @RequestBody PictureUpdateDTO request) {
        return pictureService.updatePicture(pictureId, request);
    }

    /**
     * 批量删除图片
     */
    @ApiOperation(value = "批量删除图片", notes = "批量删除多张图片")
    @ApiResponses({
        @ApiResponse(code = 200, message = "删除成功"),
        @ApiResponse(code = 400, message = "删除失败")
    })
    @PostMapping("/batch")
    @GlobalInterceptor
    public R batchDeletePictures(@RequestBody PictureBatchDeleteDTO request) {
        return pictureService.batchDeletePictures(request);
    }

    /**
     * 根据颜色搜索图片
     */
    @ApiOperation(value = "根据颜色搜索图片", notes = "根据指定的颜色值搜索相似颜色的图片")
    @ApiResponses({
        @ApiResponse(code = 200, message = "搜索成功"),
        @ApiResponse(code = 400, message = "搜索失败")
    })
    @GetMapping("/searchByColor/{color}")
    public R searchByColor(@PathVariable String color) {
        return pictureService.searchByColor(color);
    }

    /**
     * 编辑图片
     */
    @ApiOperation(value = "编辑图片", notes = "编辑图片信息和内容")
    @ApiResponses({
        @ApiResponse(code = 200, message = "编辑成功"),
        @ApiResponse(code = 400, message = "编辑失败")
    })
    @PostMapping("/edit/{pictureId}")
    @GlobalInterceptor
    public R editPicture(
            @PathVariable Long pictureId,
            @RequestParam(required = false) MultipartFile file,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String description) {
        log.info("编辑图片请求处理中 - 图片ID: {}, 文件: {}, 标签: {}, 分类: {}, 描述: {}",pictureId,file.getSize(),tags,category,description);
        return pictureService.editPicture(pictureId, file, tags, category, description);
    }

    /**
     * 下载图片
     *
     * @param url
     * @param response
     */
    @ApiOperation(value = "下载图片", notes = "下载指定URL的图片")
    @ApiResponses({
            @ApiResponse(code = 200, message = "下载成功"),
            @ApiResponse(code = 400, message = "下载失败")
    })
    @GetMapping("/download")
    public void downloadImage(@RequestParam String url, HttpServletResponse response) {
        try {
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();

            response.setContentType("image/jpeg");

            try (InputStream in = conn.getInputStream();
                 OutputStream out = response.getOutputStream()) {
                byte[] buffer = new byte[4096];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取待审核的图片列表
     */
    @ApiOperation(value = "获取待审核的图片列表", notes = "获取正在上传（待审核）的图片列表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "获取成功"),
        @ApiResponse(code = 400, message = "获取失败")
    })
    @GetMapping("/uploadings")
    @GlobalInterceptor
    public R getUploadingPictures(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) Integer reviewStatus,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String tags) {
        return pictureService.getUploadingPictures(page, pageSize, description, reviewStatus, category, tags);
    }

    /**批量抓取并创建图片
     *
     * @param pictureUploadByBatchRequest
     * @return
     */
    @ApiOperation(value = "批量抓取并创建图片", notes = "批量抓取并创建图片")
    @GetMapping("/crawler")
    public R<Integer> uploadPictureByBatch(PictureUploadByBatchDTO pictureUploadByBatchRequest) {
        ExHandler.throwIf(pictureUploadByBatchRequest == null, ResultMessageConstant.PARAMS_ERROR);
        UserSessionVO userSessionVO = (UserSessionVO) httpSession.getAttribute(KeysConstant.LOGIN_SESSION_KEY);
        return pictureService.getBingImageUrls(pictureUploadByBatchRequest, userSessionVO);
    }

    /**
     * 批量获取当前用户对图片的点赞和收藏状态
     * 
     */
    @ApiOperation(value = "批量获取当前用户对图片的点赞和收藏状态", notes = "传入图片ID列表，返回每个图片的点赞和收藏状态")
    @GetMapping("/batch-like-favorite-status")
    public R batchLikeFavoriteStatus(@RequestParam String picIds, HttpSession session) {
        UserSessionVO userSessionVO = (UserSessionVO) session.getAttribute(KeysConstant.LOGIN_SESSION_KEY);
        if (userSessionVO == null) {
            return no("未登录");
        }
        if (StringUtils.isBlank(picIds)) {
            return no("图片ID不能为空");
        }
        return pictureService.batchLikeFavoriteStatus(picIds);
    }

}